package com.example.controller;

import com.example.entity.Crud;
import com.example.mapper.CrudMapper;
import com.example.service.CrudService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import java.util.List;

@RestController
@RequestMapping("/crud")
@Slf4j
public class CrudController {

    @Autowired
    private CrudMapper crudMapper;

    @Autowired
    private CrudService crudService;

    @GetMapping("/getAll")
    public List<Crud> getAll() {
        return crudMapper.selectList(null);
    }

    @PostMapping("/update")
    public boolean updateData(@RequestBody Crud entity) {
        return crudService.updateData(entity);
    }

    @PostMapping("/add")
    public boolean addData(@RequestBody Crud entity) {
        return crudService.addData(entity);
    }

    @DeleteMapping("/delete/{id}")
    public boolean deleteData(@PathVariable Long id) {
       return (crudMapper.deleteById(id)>0);
    }
    @GetMapping("/get/{id}")
    public Crud getDataById(@PathVariable Long id) {
        return crudMapper.selectById(id);
    }
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 获取上传文件的名称
                String fileName = file.getOriginalFilename();

                // 创建目标文件存储路径
                File targetFile = new File
                        ("F:\\itModels\\login+CRUD\\finish\\vue\\src\\assets\\images\\" + fileName);

                // 将上传的文件保存到目标路径
                file.transferTo(targetFile);
                return "redirect:/success";
            } catch (IOException e) {
                log.error("文件上传失败", e);
                return "error";
            }
        } else {
            return "error";
        }
    }
}
